from app.sql.mysql_goods import insert_goods, insert_goods_spec, insert_goods_brcode
from app.utils.signUtil import sign_util
import httpx
import asyncio
from app.utils.time_util import  get_three_days_ago, get_current_time


async def task_save_good(start_time:str,end_time:str):
    try:

        async with httpx.AsyncClient() as client:
            param = sign_util(start_time, end_time, "0", "100")
            url = 'https://api.wangdian.cn/openapi2/goods_query.php'
            # 发送 GET 请求，参数通过 params 传递
            response = await client.get(
                url=url,
                params=param,
                timeout=10  # 设置超时时间（秒）
            )
            response.raise_for_status()  # 自动处理 HTTP 错误
            data = response.json()

            # 验证返回数据格式
            if "goods_list" not in data:
                raise ValueError(f"API返回格式异常: {data}")

            # 同步数据库操作改为异步执行
            loop = asyncio.get_event_loop()
            for goods in data["goods_list"]:
                try:
                    goods_spec = goods.get("spec_list", [])  # 若键不存在，默认返回空列表
                    # 使用线程池执行同步数据库操作
                    await loop.run_in_executor(None, insert_goods, goods)
                    for good_spec in goods_spec:
                        goods_brcode = good_spec.get("barcode_list", [])  # 若键不存在，默认返回空列表
                        await loop.run_in_executor(None,insert_goods_spec, good_spec)
                        for good_brcode in goods_brcode:
                            await loop.run_in_executor(None, insert_goods_brcode, good_brcode)
                except Exception as e:
                    print(f"处理商品时出错 (SKU可能为 {goods.get('goods_no')}): {e}")
                    # 可以选择记录日志或跳过当前商品，继续处理其他商品

            # print(f"成功处理 {len(data['goods_list'])} 个商品")
            return {"status": "success", "processed_count": len(data["goods_list"])}

    except httpx.HTTPStatusError as e:
        print(f"HTTP请求错误: {e.response.status_code} - {e.response.text}")
        raise
    except httpx.RequestError as e:
        print(f"网络请求异常: {e}")
        raise
    except ValueError as e:
        print(f"数据格式异常: {e}")
        raise
    except Exception as e:
        print(f"未知异常: {e}")
        raise

